<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.jpg">
  <link rel="icon" type="image/png" href="/img/favicon.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  <title>注解与反射 - Nyima&#39;s Blog</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>Nyima</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                Categories
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                Links
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/3.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-10-13 10:00">
      October 13, 2020 am
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      31
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h1 id="注解与反射"><a href="#注解与反射" class="headerlink" title="注解与反射"></a>注解与反射</h1><h1 id="一、注解"><a href="#一、注解" class="headerlink" title="一、注解"></a>一、注解</h1><h2 id="1、概念"><a href="#1、概念" class="headerlink" title="1、概念"></a>1、概念</h2><p>注解（也被称为元数据）为我们在代码中添加信息提供了一种形式化的方法，使我们可以在稍后某个时刻非常方便地使用这些数据。</p>
<h2 id="2、常见注解"><a href="#2、常见注解" class="headerlink" title="2、常见注解"></a>2、常见注解</h2><h3 id="Override"><a href="#Override" class="headerlink" title="@Override"></a>@Override</h3><p>用于标记重写某个方法</p>
<pre><code class="hljs java"><span class="hljs-meta">@Target</span>(ElementType.METHOD)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.SOURCE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Override &#123;
&#125;</code></pre>



<h3 id="Deprecated"><a href="#Deprecated" class="headerlink" title="@Deprecated"></a>@Deprecated</h3><p>用于标记已经过时的方法、属性等内容</p>
<pre><code class="hljs java"><span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Target</span>(value=&#123;CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE&#125;)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Deprecated &#123;
&#125;</code></pre>



<h3 id="SuppressWarnings"><a href="#SuppressWarnings" class="headerlink" title="@SuppressWarnings"></a>@SuppressWarnings</h3><p>用于镇压警告</p>
<pre><code class="hljs java"><span class="hljs-meta">@Target</span>(&#123;TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE&#125;)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.SOURCE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> SuppressWarnings &#123;
    String[] value();
&#125;</code></pre>



<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>可以看出注解有这么几个部分</p>
<ul>
<li><p>@interface + 注解名称</p>
</li>
<li><p>@Target : 注解的作用域</p>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> ElementType &#123;
    TYPE,

    FIELD,

    METHOD,

    PARAMETER,

    CONSTRUCTOR,

    LOCAL_VARIABLE,

    ANNOTATION_TYPE,

    PACKAGE,

	<span class="hljs-comment">// JDK 8 以后添加的注解</span>
    TYPE_PARAMETER,
    
    TYPE_USE
&#125;</code></pre>



</li>
</ul>
<ul>
<li><p>@Retention : 注解的生命周期</p>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> RetentionPolicy &#123;
    SOURCE,

    CLASS,

    RUNTIME
&#125;</code></pre>



</li>
</ul>
<h2 id="3、元注解"><a href="#3、元注解" class="headerlink" title="3、元注解"></a>3、元注解</h2><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><ul>
<li><p>元注解的目的就是<strong>注解其他注解</strong>，Java提供了4个meta-annotation，他们被用来对其他注解提供说明</p>
</li>
<li><p>他们可以在 java.lang.annotation 包下被找到</p>
</li>
</ul>
<h3 id="注解"><a href="#注解" class="headerlink" title="注解"></a>注解</h3><h4 id="Target"><a href="#Target" class="headerlink" title="@Target"></a>@Target</h4><p>用于标明注解的作用范围</p>
<pre><code class="hljs java"><span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Target</span>(ElementType.ANNOTATION_TYPE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Target &#123;
    ElementType[] value();
&#125;</code></pre>



<h4 id="Retention"><a href="#Retention" class="headerlink" title="@Retention"></a>@Retention</h4><p>用于标明注解的生命周期</p>
<pre><code class="hljs java"><span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Target</span>(ElementType.ANNOTATION_TYPE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Retention &#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * Returns the retention policy.</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> the retention policy</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function">RetentionPolicy <span class="hljs-title">value</span><span class="hljs-params">()</span></span>;
&#125;</code></pre>



<h4 id="Documented"><a href="#Documented" class="headerlink" title="@Documented"></a>@Documented</h4><p>用于标明该注解将会被包含在javadoc中</p>
<pre><code class="hljs java"><span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Target</span>(ElementType.ANNOTATION_TYPE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Documented &#123;
&#125;</code></pre>



<h4 id="Inherited"><a href="#Inherited" class="headerlink" title="@Inherited"></a>@Inherited</h4><p>用于标明子类可以继承父类的该注解</p>
<pre><code class="hljs java"><span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Target</span>(ElementType.ANNOTATION_TYPE)
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Inherited &#123;
&#125;</code></pre>



<h2 id="4、自定义注解"><a href="#4、自定义注解" class="headerlink" title="4、自定义注解"></a>4、自定义注解</h2><h3 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h3><ul>
<li>通过 <strong>@interface</strong> 关键字定义注解名称。此时会自动继承 <strong>java.lang.annotation.Annotation</strong></li>
<li>需要给定一个或多个元注解</li>
<li>自定义注解的参数声明方式是 ： <strong>参数类型 参数名称 ();</strong> ，如 String name();<ul>
<li>可以定义默认值，如 String name () default = “Nyima”;</li>
</ul>
</li>
</ul>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo1</span> </span>&#123;
   <span class="hljs-meta">@MyAnnotation</span>(name = <span class="hljs-string">"Main Method"</span>)
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
      
   &#125;
&#125;

<span class="hljs-meta">@Target</span>(value = &#123;ElementType.METHOD&#125;)
<span class="hljs-meta">@Retention</span>(value =  RetentionPolicy.RUNTIME)
<span class="hljs-meta">@interface</span> MyAnnotation &#123;
   <span class="hljs-function">String <span class="hljs-title">name</span><span class="hljs-params">()</span></span>;
   <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> 0</span>;
&#125;</code></pre>



<h1 id="二、反射"><a href="#二、反射" class="headerlink" title="二、反射"></a>二、反射</h1><h2 id="1、Java-Reflection"><a href="#1、Java-Reflection" class="headerlink" title="1、Java Reflection"></a>1、Java Reflection</h2><ul>
<li><p>Reflection 是 Java被视为动态语言（运行时改变其结构）的关键，反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息，并能直接操作任意对象的内部属性及方法</p>
</li>
<li><p>加载完类之后，在对内存的方法去中就产生了一个Class类型的对象（一个类只有一个Class对象），这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子，透过这个镜子看到类的结构，所以我们形象地称之为：反射</p>
</li>
</ul>
<p>正常方式创建对象：</p>
<ul>
<li>引入需要的包的名称</li>
<li>通过new实例化</li>
<li>获得实例化对象</li>
</ul>
<p>反射方式创建对象：</p>
<ul>
<li>实例化对象</li>
<li>getClass()方法</li>
<li>得到完整的包的名称</li>
</ul>
<h2 id="2、优缺点"><a href="#2、优缺点" class="headerlink" title="2、优缺点"></a>2、优缺点</h2><h3 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h3><ul>
<li>可以实现动态创建对象和编译，体现出很大的灵活性</li>
<li>对性能有所影响</li>
</ul>
<h2 id="3、相关API"><a href="#3、相关API" class="headerlink" title="3、相关API"></a>3、相关API</h2><ul>
<li>java.lang.Class：代表一个类</li>
<li>java.lang.reflect.Method：代表类的方法</li>
<li>java.lang.reflect.Field：代表类的成员变量</li>
<li>java.lang.reflect.Constructor：代表类的构造器</li>
</ul>
<h2 id="4、使用"><a href="#4、使用" class="headerlink" title="4、使用"></a>4、使用</h2><h3 id="通过反射创建对象"><a href="#通过反射创建对象" class="headerlink" title="通过反射创建对象"></a>通过反射创建对象</h3><p>获取类的Class对象有<strong>三种方法</strong></p>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo2</span> </span>&#123;
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException </span>&#123;
		<span class="hljs-comment">// 通过反射获取多个User类的Class对象，看其是否相等</span>
		<span class="hljs-comment">// 通过Class类的forName()方法来获得类的Class对象</span>
		Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
		<span class="hljs-comment">// 通过类的class属性获得Class对象</span>
		Class c2 = User<span class="hljs-class">.<span class="hljs-keyword">class</span></span>;
		<span class="hljs-comment">// 通过对象的getClass()方法获得Class对象</span>
		Class c3 = <span class="hljs-keyword">new</span> User().getClass();
		System.out.println(c1.hashCode());
		System.out.println(c2.hashCode());
		System.out.println(c3.hashCode());
		c3.getClass();
	&#125;
&#125;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;
	<span class="hljs-keyword">private</span> String name;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">()</span> </span>&#123;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
		<span class="hljs-keyword">this</span>.age = age;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> age;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.age = age;
	&#125;
&#125;</code></pre>

<p><strong>运行结果</strong></p>
<pre><code class="hljs angelscript"><span class="hljs-number">1163157884</span>
<span class="hljs-number">1163157884</span>
<span class="hljs-number">1163157884</span></code></pre>

<p><strong>结论</strong>：可以看出，通过反射获取某个类的Class对象，获取的对象都是相同的。也就是每个类有且只有一个Class对象</p>
<h3 id="Class类"><a href="#Class类" class="headerlink" title="Class类"></a>Class类</h3><p>Object类中定义以下方法</p>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">native</span> Class&lt;?&gt; getClass();</code></pre>

<p>这个方法的返回值就是Class类，<strong>Class类是反射的源头</strong></p>
<ul>
<li>Class本身也是一个类</li>
<li>Class对象<strong>只能由系统建立对象</strong></li>
<li>一个加载的类在<strong>JVM中只会有一个Class实例</strong></li>
<li>一个Class对象对应的是一个 加载到JVM中的一个.class文件</li>
<li>每个类的实例都会记得自己是由哪个Class实例所生成</li>
<li>通过Class可以完整地得到一个类中的<strong>所有被加载的结构</strong></li>
<li><strong>Class类是Reflection的根源</strong>，针对任何你想动态加载、运行的类，唯有先获得相应的对象</li>
</ul>
<h4 id="拥有Class对象的类型"><a href="#拥有Class对象的类型" class="headerlink" title="拥有Class对象的类型"></a>拥有Class对象的类型</h4><p>class：外部类、内部内、静态内部类等</p>
<p>interface：接口</p>
<p>[]：数组</p>
<p>enum：枚举</p>
<p>annotation：注解@interface</p>
<p>primitive type：基本数据类型</p>
<p>void</p>
<pre><code class="hljs javapublic">public class Demo3 &#123;
   public static void main(String[] args) &#123;
      Class c1 &#x3D; Object.class;
      Class c2 &#x3D; Collection.class;
      Class c3 &#x3D; int[].class;
      Class c4 &#x3D; ElementType.class;
      Class c5 &#x3D; SuppressWarnings.class;
      Class c6 &#x3D; Integer.class;
      Class c7 &#x3D; void.class;
   &#125;
&#125;</code></pre>



<h3 id="通过反射获得类的信息"><a href="#通过反射获得类的信息" class="headerlink" title="通过反射获得类的信息"></a>通过反射获得类的信息</h3><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo4</span> </span>&#123;
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> NoSuchMethodException, NoSuchFieldException, ClassNotFoundException </span>&#123;
      Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
      
      <span class="hljs-comment">// 获得所有公共属性</span>
      Field[] fields = c1.getFields();
      
      <span class="hljs-comment">// 获得所有属性</span>
      Field[] declaredFields = c1.getDeclaredFields();
      
      <span class="hljs-comment">// 获得指定属性</span>
      Field name = c1.getDeclaredField(<span class="hljs-string">"name"</span>);

      <span class="hljs-comment">// 获得所有公有方法</span>
      Method[] methods = c1.getMethods();
      
      <span class="hljs-comment">// 获得所有方法</span>
      Method[] declaredMethods = c1.getDeclaredMethods();
      
      <span class="hljs-comment">// 获得指定方法</span>
      Method setAge = c1.getDeclaredMethod(<span class="hljs-string">"setAge"</span>, <span class="hljs-keyword">int</span><span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
   &#125;
&#125;</code></pre>



<h3 id="通过反射获得类的对象"><a href="#通过反射获得类的对象" class="headerlink" title="通过反射获得类的对象"></a>通过反射获得类的对象</h3><p><strong>通过newInstance()方法</strong></p>
<ul>
<li>类必须含有一个<strong>无参构造器</strong></li>
<li>类的构造器的访问权限要足够</li>
</ul>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo5</span> </span>&#123;
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException </span>&#123;
      Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
      User user = (User) c1.newInstance();
      System.out.println(user);
   &#125;
&#125;</code></pre>

<p>如果重载了一个方法的构造方法，最好再补上一个无参构造函数</p>
<p><strong>通过获得类的构造器，再进行初始化</strong></p>
<pre><code class="hljs typescript"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Demo5 &#123;
   <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">void</span> main(<span class="hljs-built_in">String</span>[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException &#123;
      Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
      Constructor <span class="hljs-keyword">constructor</span> = c1.getDeclaredConstructor(<span class="hljs-params"><span class="hljs-built_in">String</span>.<span class="hljs-keyword">class</span>, int.<span class="hljs-keyword">class</span></span>);
      User user2 = (User) <span class="hljs-keyword">constructor</span>.newInstance(<span class="hljs-params">"Nyima", 20</span>);
      System.out.println(user2.getAge());
   &#125;
&#125;</code></pre>



<p><strong>总结</strong>：获得类的实例的步骤</p>
<ul>
<li>通过类的Class对象</li>
<li>如果想通过调用<strong>无参构造方法</strong>创建实例<ul>
<li>直接调用Class对象的newInstance()方法</li>
<li>将返回值强转为对应的类型</li>
</ul>
</li>
<li>如果想通过<strong>有参构造方法</strong>创建实例<ul>
<li>调用Class对象的getDeclaredConstructor()并传入构造方法相应的参数的类型</li>
<li>通过获得的有参构造器，调用newInstance()方法，传入相应参数</li>
<li>将返回值强转为对应的类型</li>
</ul>
</li>
</ul>
<h3 id="通过反射调用类的方法"><a href="#通过反射调用类的方法" class="headerlink" title="通过反射调用类的方法"></a>通过反射调用类的方法</h3><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo5</span> </span>&#123;
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException </span>&#123;
      Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
      User user = (User) c1.newInstance();
      Method setName = c1.getDeclaredMethod(<span class="hljs-string">"setName"</span>, String<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
      setName.invoke(user, <span class="hljs-string">"Nyima"</span>);
      System.out.println(user.getName());

   &#125;
&#125;</code></pre>

<p><strong>步骤</strong></p>
<ul>
<li>获得类的Class对象</li>
<li>调用Class对象的newInstance()方法，获取类的对象</li>
<li>调用Class对象的getDeclaredMethod()方法</li>
<li>调用返回对象的invoke()方法，传入所需的参数（参数包含对哪个对象调用该方法），如 setName.invoke(<strong>user</strong>, “Nyima”);</li>
</ul>
<h3 id="通过反射设置属性值"><a href="#通过反射设置属性值" class="headerlink" title="通过反射设置属性值"></a>通过反射设置属性值</h3><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo5</span> </span>&#123;
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException </span>&#123;
      Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.User"</span>);
      User user = (User) c1.newInstance();
      Field name = c1.getDeclaredField(<span class="hljs-string">"name"</span>);
      name.set(user, <span class="hljs-string">"Nyima2"</span>);
      System.out.println(user.getName());
   &#125;
&#125;</code></pre>

<p><strong>步骤</strong></p>
<ul>
<li>获得类的Class对象</li>
<li>调用Class对象的newInstance()方法，获取类的对象</li>
<li>调用Class对象的getDeclaredField()方法，获取属性</li>
<li>调用属性对象的set()方法进行赋值<ul>
<li>如果是<strong>私有属性</strong>，还需要调用name.setAccessible(true);方法进行设定</li>
</ul>
</li>
</ul>
<h3 id="通过获得注解信息"><a href="#通过获得注解信息" class="headerlink" title="通过获得注解信息"></a>通过获得注解信息</h3><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo6</span> </span>&#123;
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException </span>&#123;
		Class c1 = Class.forName(<span class="hljs-string">"main.study.day4.Student"</span>);
		Student student = (Student) c1.newInstance();
		<span class="hljs-comment">// 获得类的注解</span>
		Annotation[] declaredAnnotations = c1.getDeclaredAnnotations();
		System.out.println(Arrays.toString(declaredAnnotations));

		<span class="hljs-comment">// 获得属性上的注解</span>
		Field name = c1.getDeclaredField(<span class="hljs-string">"name"</span>);
		Annotation annotation = name.getAnnotation(FieldAnnotation<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
		System.out.println(annotation);

		<span class="hljs-comment">// 获得方法的注解</span>
		Method getName = c1.getDeclaredMethod(<span class="hljs-string">"getName"</span>);
		MethodAnnotation methodAnnotation = getName.getAnnotation(MethodAnnotation<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
		System.out.println(methodAnnotation);
	&#125;
&#125;

<span class="hljs-meta">@ClassAnnotation</span>(name = <span class="hljs-string">"myStudent"</span>)
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>&#123;

	<span class="hljs-meta">@FieldAnnotation</span>(name = <span class="hljs-string">"name"</span>)
	<span class="hljs-keyword">private</span> String name;
	<span class="hljs-meta">@FieldAnnotation</span>(name = <span class="hljs-string">"age"</span>)
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">()</span> </span>&#123;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
		<span class="hljs-keyword">this</span>.age = age;
	&#125;

	<span class="hljs-meta">@MethodAnnotation</span>(name = <span class="hljs-string">"getName"</span>)
	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> age;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.age = age;
	&#125;
&#125;

<span class="hljs-meta">@Target</span>(&#123;ElementType.TYPE&#125;)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-comment">/**</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Nyima</span>
<span class="hljs-comment"> * 类的注解</span>
<span class="hljs-comment"> */</span>
<span class="hljs-meta">@interface</span> ClassAnnotation &#123;
	<span class="hljs-function">String <span class="hljs-title">name</span><span class="hljs-params">()</span></span>;
&#125;

<span class="hljs-meta">@Target</span>(&#123;ElementType.FIELD&#125;)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-comment">/**</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Nyima</span>
<span class="hljs-comment"> * 属性的注解</span>
<span class="hljs-comment"> */</span>
<span class="hljs-meta">@interface</span> FieldAnnotation &#123;
	<span class="hljs-function">String <span class="hljs-title">name</span><span class="hljs-params">()</span></span>;
&#125;

<span class="hljs-meta">@Target</span>(&#123;ElementType.METHOD&#125;)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-comment">/**</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Nyima</span>
<span class="hljs-comment"> * 方法的注解</span>
<span class="hljs-comment"> */</span>
<span class="hljs-meta">@interface</span> MethodAnnotation &#123;
	<span class="hljs-function">String <span class="hljs-title">name</span><span class="hljs-params">()</span></span>;
&#125;</code></pre>

<p><strong>步骤</strong></p>
<ul>
<li>先获取到对应的类，如<ul>
<li>想获得类注解，需要先获得Class类对象</li>
<li>想获得属性的注解，需要先获得对应的属性</li>
<li>想获得方法的注解，需要先获得对应的方法</li>
<li>…</li>
</ul>
</li>
<li>通过对应的对象调用getDeclaredAnnotation()或者其他获取注解的方法，并传入需要的参数即可</li>
</ul>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2020/10/26/%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">集合源码</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2020/09/12/%E6%8C%87%E4%BB%A4%E6%B5%81%E7%A8%8B%E5%92%8C%E4%B8%AD%E6%96%AD/">
                        <span class="hidden-mobile">指令流程和中断</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div class="disqus" style="width:100%">
    <div id="disqus_thread"></div>
    <script type="text/javascript">
      function loadDisqus() {
        var disqus_config = function () {
          this.page.url = 'http://nyimac.gitee.io/2020/10/13/注解与反射/';
          this.page.identifier = '/2020/10/13/注解与反射/';
        };
        (function () {
          var d = document,
            s = d.createElement('script');
          s.src = '//' + '' + '.disqus.com/embed.js';
          s.setAttribute('data-timestamp', new Date());
          (d.head || d.body).appendChild(s);
        })();
      }
      createObserver(loadDisqus, 'disqus_thread');
    </script>
    <noscript>Please enable JavaScript to view the
      <a href="https://disqus.com/?ref_noscript" target="_blank" rel="nofollow noopener noopener">comments powered by Disqus.</a>
    </noscript>
  </div>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "注解与反射&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>

















  
    <!-- Baidu Analytics -->
    <script defer>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?ba41ec605b9b7320e120275462e4035b";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  

  

  

  

  





</body>
</html>
